package http_client

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/opentracing/opentracing-go"
	"io"
	"io/ioutil"
	"net/http"
)

type Request struct {
	*http.Request
}
type Response struct {
	*http.Response
}

func (req *Request) Send() (*Response, error) {
	client := new(http.Client)
	res, err := client.Do(req.Request)
	if err != nil {
		return nil, err
	}
	return &Response{
		Response: res,
	}, err
}

func (req *Request) Trace(ctx context.Context) error {
	span := opentracing.SpanFromContext(ctx)
	if span == nil {
		return errors.New("上下文中没有span")
	}
	tracer := opentracing.GlobalTracer()
	err := tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
	if err != nil {
		return err
	}
	return nil
}

func (res *Response) Json(pointer interface{}) error {
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err
	}
	return json.Unmarshal(body, pointer)
}

func (res *Response) String() (string, error) {
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(body), err
}

func (res *Response) Byte() ([]byte, error) {
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return body, err
}

func New(method string, url string, body io.Reader) (*Request, error) {
	req, err := http.NewRequest(method, url, body)

	if err != nil {
		return nil, err
	}
	r := &Request{
		Request: req,
	}
	return r, nil
}
